// 工厂列表菜单
import React, {useState, useEffect} from 'react';
import {connect} from 'react-redux';
import {Progress, Input, Upload, Button, Row, Col, Form, Cascader, message, Select} from 'antd';
import {PlusOutlined} from '@ant-design/icons';
import {config, mUrl} from "../../../config";
import mUtils from "../../../utils/utils";
import {get, post} from "../../../utils";

// 点击新增厂家
const Page = (props) => {
    const [form] = Form.useForm();
    const [tag, setTag] = useState([]); // 标签列表
    const [labelIndex, setLabelIndex] = useState(undefined);
    const [orgstate, setOrgstate] = useState(undefined);
    const [tagValue, setTagValue] = useState(undefined); // 新增标签的内容
    const [mainImgFileList, setMainImgFileList] = useState([]); // 主图
    const [businessFileList, setBusinessFileList] = useState([]); // 营业执照
    const [introduceImgFileList, setIntroduceImgFileList] = useState([]); // 介绍图
    const [codeImgFileList, setCodeImgFileList] = useState([]); // 微信二维码
    const [videoFileList, setVideoFileList] = useState([]); // 视频
    const [options, setOptions] = useState([]); // 分类列表
    const [detail, setDetail] = useState({});
    useEffect(() => {
        if (props.location.state.orgid) {
            setUpdateDetail(props.location.state);
        }
        searchTypeList();
    }, []);

    const setUpdateDetail = (data) => {
        setDetail(data);
        const formDate = {
            orgname: data.orgname,
            linkman: data.linkman,
            area: data.area,
            // appletslogin: data.appletslogin,
            linkphone: data.linkphone,
            orgaddress: data.orgaddress,
            remark: data.remark,
        };
        const mainImgFileList = [];
        const businessFileList = [];
        const codeImgFileList = [];
        const introduceImgFileList = [];
        const videoFileList = [];
        const setImgPush = (img, list, name) => {
            const imgList = img.split(',');
            imgList.forEach((item, index) => {
                list.push({
                    uid: name + index,
                    name: name + index,
                    file_name: item,
                    status: 'done',
                    url: item,
                    file_path: item
                });
            });
        };
        if (data.imageurl) {
            setImgPush(data.imageurl, mainImgFileList, 'imageurl');
            setMainImgFileList(mainImgFileList);
        }
        if (data.businessurl) {
            setImgPush(data.businessurl, businessFileList, 'businessurl');
            setBusinessFileList(businessFileList);
        }
        if (data.qrcordurl) {
            setImgPush(data.qrcordurl, codeImgFileList, 'qrcordurl');
            setCodeImgFileList(codeImgFileList);
        }
        if (data.detailurl) {
            setImgPush(data.detailurl, introduceImgFileList, 'detailurl');
            setIntroduceImgFileList(introduceImgFileList);
        }
        if (data.videourl) {
            setImgPush(data.videourl, videoFileList, 'videourl');
            setVideoFileList(videoFileList);
        }
        if (data.orgLabelList.length > 0) {
            let tagList = [];
            data.orgLabelList.forEach((item) => {
                tagList.push(item.labelname);
            });
            setTag(tagList);
        }
        if (data.orgClassifyList.length > 0) {
            const classList = [];
            data.orgClassifyList.forEach((item) => {
                classList.push(item.classifyid);
                if (item.subClassifyList) {
                    item.subClassifyList.forEach((sItem) => {
                        classList.push(sItem.classifyid);
                    });
                }
            });
            formDate.classification = classList;
        }
        form.setFieldsValue(formDate);
    };

    const uploadButton = ( // 选择图片按钮
        <div>
            <PlusOutlined/>
            <div style={{marginTop: 8}}>请选择</div>
        </div>
    );

    const searchTypeList = () => {
        get(mUrl.searchAllClassify, {}).then((res) => {
            const data = res.data.map((item) => {
                // const list = item.subClassifyList.map((sItem) => {
                //     return {
                //         value: sItem.classifyid,
                //         label: sItem.name,
                //     };
                // });
                return {
                    value: item.classifyid,
                    label: item.name,
                    // children: list
                };
            });
            setOptions(data);
        });
    };

    const selectImg = ({fileList}, id) => {
        if (id === 1) { // 选择主图
            setMainImgFileList(fileList);
        } else if (id === 2) { // 选择介绍图
            setIntroduceImgFileList(fileList);
        } else if (id === 3) { // 选择微信二维码
            setCodeImgFileList(fileList);
        } else if (id === 4) { // 选择视频
            setVideoFileList(fileList);
        } else if (id === 5) { // 选择视频
            setBusinessFileList(fileList);
        }
    };
    // 预览图片
    const handlePreview = async file => {
        let src = file.url;
        if (!src) {
            src = await new Promise(resolve => {
                const reader = new FileReader();
                reader.readAsDataURL(file.originFileObj);
                reader.onload = () => resolve(reader.result);
            });
        }
        const image = new Image();
        image.src = src;
        const imgWindow = window.open(src);
        imgWindow.document.write(image.outerHTML);
    };

    

    const submit = (type) => {
        setOrgstate(type);
        setTimeout(() => {
            form.submit();
        }, 200);
    };

    const onFinish = async (value) => {
        if (mainImgFileList.length) {
            value.imageurl = mUtils.setImageUrl(mainImgFileList);
        } else {
            value.imageurl = '';
        }
        // else {
        //     message.error('请选择主图片');
        //     return;
        // }
        if (businessFileList.length) {
            value.businessurl = mUtils.setImageUrl(businessFileList);
        } else {
            value.businessurl = '';
        }
        // else {
        //     message.error('请选择营业执照');
        //     return;
        // }
        if (value.classification) {
            const orgClassifyList = [];
            value.classification.forEach((item) => {
                orgClassifyList.push({classifyid: item});
            });
            value.orgClassifyList = orgClassifyList;
            delete value.classification;
        }
        if (tag.length > 0) {
            const orgLabelList = [];
            tag.forEach((item) => {
                orgLabelList.push({labelname: item});
            });
            value.orgLabelList = orgLabelList;
        }
        if (introduceImgFileList.length) {
            value.detailurl = mUtils.setImageUrl(introduceImgFileList);
        } else {
            value.detailurl = '';
        }
        if (codeImgFileList.length) {
            value.qrcordurl = mUtils.setImageUrl(codeImgFileList);
        } else {
            value.qrcordurl = '';
        }
        if (videoFileList.length) {
            value.videourl = mUtils.setImageUrl(videoFileList);
        } else {
            value.videourl = '';
        }
        value.orgtype = 1;
        value.orgstate = orgstate + '';
        let url = mUrl.updateOrganization;
        value.orgid = detail.orgid;
        value.appletslogin = detail.appletslogin;
        const res = await post(url, value);
        if (res.state === 1) {
            message.info('修改成功');
            window.closeWin();
            window.onSelectWin({title: '厂家列表', path: '/main/factoryList', page: '/main/factoryList'});
        }
    };

    return (
        <div style={{padding: 14, background: '#fff', minHeight: 360}}>
            <label><p>厂家管理 / {detail.orgid ? '编辑厂家' : '添加厂家'}</p></label>
            <Row>
                <Col span={10}>
                    <Form form={form} onFinish={onFinish}>
                        <Form.Item
                            label='分类'
                            name='classification'
                            // rules={[{required: true, message: '请选择分类'}]}
                            labelCol={{span: 5}}
                        >
                            <Select
                                mode="multiple"
                                style={{width: 200}}
                                placeholder="请选择"
                            >
                                {
                                    options.map((item) => {
                                        return (
                                            <Select.Option key={item.value}>{item.label}</Select.Option>
                                        );
                                    })
                                }
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label='工厂名称'
                            name='orgname'
                            rules={[{required: true, message: '请输入工厂名称'}]}
                            labelCol={{span: 5}}
                        >
                            <Input style={{width: 200}}/>
                        </Form.Item>
                        <Form.Item
                            label='联系人'
                            name='linkman'
                            // rules={[{required: true, message: '请输入联系人'}]}
                            labelCol={{span: 5}}
                        >
                            <Input style={{width: 200}}/>
                        </Form.Item>
                        {/*<Form.Item*/}
                        {/*    label='账号'*/}
                        {/*    name='appletslogin'*/}
                        {/*    rules={[{required: true, message: '请输入账号'}]}*/}
                        {/*    labelCol={{span: 5}}*/}
                        {/*>*/}
                        {/*    <Input style={{width: 200}}/>*/}
                        {/*</Form.Item>*/}
                        <Form.Item
                            label='电话'
                            name='linkphone'
                            // rules={[{required: true, message: '请输入电话'}]}
                            labelCol={{span: 5}}
                        >
                            <Input style={{width: 200}}/>
                        </Form.Item>
                        <Form.Item
                            label='标签'
                            labelCol={{span: 5}}
                        >
                            {
                                tag.map((item, index) => {
                                    return (
                                        <Button
                                            type={labelIndex === index ? 'primary' : ''}
                                            onClick={() => {
                                                setLabelIndex(index + '');
                                            }}
                                            key={item + index}>
                                            {item}
                                        </Button>
                                    );
                                })
                            }
                            <div>
                                <Input
                                    size='small'
                                    style={{width: 100, margin: 10, marginLeft: 0}}
                                    value={tagValue}
                                    onChange={(e) => {
                                        setTagValue(e.target.value);
                                    }}
                                />
                                <Button
                                    type='primary'
                                    size='small'
                                    style={{marginTop: 10}}
                                    onClick={() => {
                                        setTag([
                                            ...tag,
                                            tagValue
                                        ]);
                                        setTagValue(undefined);
                                    }}
                                >新增标签</Button>
                                <Button
                                    type='primary'
                                    size='small'
                                    disabled={!labelIndex}
                                    style={{marginLeft: 10, marginTop: 10}}
                                    onClick={() => {
                                        tag.splice(labelIndex, 1);
                                        setTag([...tag]);
                                        setLabelIndex(undefined);
                                    }}
                                >删除</Button>
                            </div>
                        </Form.Item>
                        <Form.Item
                            label='地址'
                            name='orgaddress'
                            // rules={[{required: true, message: '请选择分类'}]}
                            labelCol={{span: 5}}
                        >
                            <Input style={{width: 200}}/>
                        </Form.Item>
                        <Form.Item
                            label='厂家区域'
                            name='area'
                            // rules={[{required: true, message: '请选择分类'}]}
                            labelCol={{span: 5}}
                        >
                            <Input style={{width: 200}}/>
                        </Form.Item>
                        <Form.Item
                            label='简介'
                            name='remark'
                            labelCol={{span: 5}}
                        >
                            <Input.TextArea rows={5}/>
                        </Form.Item>
                        <Form.Item
                            label='主图'
                            labelCol={{span: 5}}
                        >
                            <Upload
                                action={config.serverUrl + '/api/upload/uploadfile?token=' + mUtils.getToken()}
                                listType="picture-card"
                                fileList={mainImgFileList}
                                onPreview={handlePreview}
                                accept=".jpeg,.jpg,.png"
                                onChange={(file) => {
                                    selectImg(file, 1);
                                }}
                            >
                                {mainImgFileList.length >= 5 ? null : uploadButton}
                            </Upload>
                            <span style={{color: 'red'}}>最多可上传5个，建议尺寸：500*250px</span>
                        </Form.Item>
                        <Form.Item
                            label='营业执照'
                            labelCol={{span: 5}}
                        >
                            <Upload
                                action={config.serverUrl + '/api/upload/uploadfile?token=' + mUtils.getToken()}
                                listType="picture-card"
                                fileList={businessFileList}
                                onPreview={handlePreview}
                                accept=".jpeg,.jpg,.png"
                                onChange={(file) => {
                                    selectImg(file, 5);
                                }}
                            >
                                {businessFileList.length >= 2 ? null : uploadButton}
                            </Upload>
                            <span style={{color: 'red'}}>最多可上传2个，建议尺寸：500*250px</span>
                        </Form.Item>
                        <Form.Item
                            label='介绍图'
                            labelCol={{span: 5}}
                        >
                            <Upload
                                action={config.serverUrl + '/api/upload/uploadfile?token=' + mUtils.getToken()}
                                accept=".jpeg,.jpg,.png"
                                listType="picture-card"
                                fileList={introduceImgFileList}
                                onPreview={handlePreview}
                                onChange={(file) => {
                                    selectImg(file, 2);
                                }}
                            >
                                {introduceImgFileList.length >= 1 ? null : uploadButton}
                            </Upload>
                        </Form.Item>
                        <Form.Item
                            label='微信二维码'
                            labelCol={{span: 5}}
                        >
                            <Upload
                                action={config.serverUrl + '/api/upload/uploadfile?token=' + mUtils.getToken()}
                                accept=".jpeg,.jpg,.png"
                                listType="picture-card"
                                fileList={codeImgFileList}
                                onPreview={handlePreview}
                                onChange={(file) => {
                                    selectImg(file, 3);
                                }}
                            >
                                {codeImgFileList.length >= 1 ? null : uploadButton}
                            </Upload>
                        </Form.Item>
                        <Form.Item
                            label='视频'
                            labelCol={{span: 5}}
                        >
                            {videoFileList.length >= 1 ?
                                (
                                    <div
                                        style={{
                                            display: 'flex',
                                            flexWrap: 'wrap',
                                            marginTop: 15,
                                            marginBottom: 15
                                        }}>
                                        {
                                            videoFileList.map((item, index) => {
                                                let url = item.url;
                                                if (item.response) {
                                                    url = item.response.data.file_url;
                                                }
                                                return (
                                                    <div className="clearfix upload-background"
                                                         key={'video' + index}>
                                                        <br/>
                                                        {
                                                            url ?
                                                                (
                                                                    <video width="240" height="160" controls>
                                                                        <source src={url}
                                                                                type="video/ogg"/>
                                                                        <source src={url}
                                                                                type="video/mp4"/>
                                                                        <source src={url}
                                                                                type="video/webm"/>
                                                                        <object src={url}
                                                                                width="240"
                                                                                height="160">
                                                                            <embed width="240" height="160"
                                                                                   src={url}/>
                                                                        </object>
                                                                    </video>
                                                                ) :
                                                                (<Progress/>)
                                                        }
                                                        <Button onClick={() => {
                                                            setVideoFileList([]);
                                                        }}
                                                                style={{
                                                                    marginLeft: '10px',
                                                                    color: 'red',
                                                                    padding: '5px'
                                                                }}>删除</Button>
                                                    </div>
                                                );
                                            })
                                        }
                                    </div>
                                ) : ''}
                            {
                                videoFileList.length === 0 ?
                                    (
                                        <Upload
                                            action={config.serverUrl + '/api/upload/uploadfile?token=' + mUtils.getToken()}
                                            name='file'
                                            accept=".mp4, .mov, .m4v, .3gp, .avi, .m3u8, .webm"
                                            listType="picture-card"
                                            fileList={videoFileList}
                                            onPreview={handlePreview}
                                            onChange={(file) => {
                                                selectImg(file, 4);
                                            }}
                                        >
                                            {videoFileList.length >= 1 ? null : uploadButton}
                                        </Upload>
                                    ) : null
                            }
                        </Form.Item>
                        <Form.Item style={{marginTop: 10, textAlign: 'center'}}>
                            <Button
                                style={{marginRight: 15}}
                                onClick={() => submit(0)}
                                type={'primary'}
                            >提交成为待认证厂家</Button>
                            {
                                businessFileList.length > 0 &&
                                <Button
                                    style={{marginRight: 15}}
                                    onClick={() => submit(1)}
                                    type={'primary'}
                                >提交并审核通过</Button>
                            }
                            <Button
                                onClick={_ => {
                                    window.closeWin();
                                    window.onSelectWin({
                                        title: '厂家列表',
                                        path: '/main/factoryList',
                                        page: '/main/factoryList'
                                    });
                                }}
                            >取消</Button>
                        </Form.Item>
                    </Form>
                </Col>
            </Row>
        </div>
    );
};

export default connect()(Page);